package pl.edu.mimuw.irs.rcp.controller.part;

import java.util.LinkedHashSet;
import java.util.Set;

import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;

import pl.edu.mimuw.irs.core.model.petrinet.Transition;
import pl.edu.mimuw.irs.rcp.view.figure.FigureWrapper;
import pl.edu.mimuw.irs.rcp.view.figure.TGTransitionShape;


/**
 * @author Jakub Rauch
 * Created on: 2009-05-28
 */
public class TGTransitionEditPart extends TransitionEditPart implements
		TokenGameEditPart {

	// *** Attributes

	// *** Methods

	protected NodeShape getNodeShape() {
		return NodeShape.TGTRANSITION;
	}
	
	@Override
	protected void refreshVisuals() {
		Transition transition = (Transition)getNode();
		FigureWrapper wrapper = (FigureWrapper)getFigure();
		TGTransitionShape shape = (TGTransitionShape) wrapper.getFigure();
		
		shape.setActive(transition.isActive());
		
		super.refreshVisuals();
	}
	
	public void performRequest(Request req) {
		if (req.getType().equals(RequestConstants.REQ_OPEN)){
			Transition transition = (Transition)getNode();
			if (transition.isActive()) transition.invoke();
			refreshTokens();
			refreshTransitions();
		}
		super.performRequest(req);
	}

	public void refreshTokens() {
		for (Object editPart : getSourceConnections()) {
			ArcEditPart arcEditPart = (ArcEditPart) editPart;
			arcEditPart.getTarget().refresh();
		}
		for (Object editPart : getTargetConnections()) {
			ArcEditPart arcEditPart = (ArcEditPart) editPart;
			arcEditPart.getSource().refresh();
		}
	}
	
	private void refreshTransitions() {
		Set<TransitionEditPart> transitions = new LinkedHashSet<TransitionEditPart>();
		for (Object editPart : getSourceConnections()) {
			ArcEditPart arcEditPart = (ArcEditPart) editPart;
			PlaceEditPart placeEditPart = (PlaceEditPart) arcEditPart.getTarget();
			// These transitions can be activated
			for (Object editPart2 : placeEditPart.getSourceConnections()) {
				ArcEditPart arcEditPart2 = (ArcEditPart) editPart2;
				TransitionEditPart transitionEditPart = (TransitionEditPart) arcEditPart2.getTarget();
				if (!transitions.contains(transitionEditPart)) transitions.add(transitionEditPart);
			}
		}
		for (Object editPart : getTargetConnections()) {
			ArcEditPart arcEditPart = (ArcEditPart) editPart;
			PlaceEditPart placeEditPart = (PlaceEditPart) arcEditPart.getSource();
			// Some of these transitions can be deactivated
			for (Object editPart2 : placeEditPart.getSourceConnections()) {
				ArcEditPart arcEditPart2 = (ArcEditPart) editPart2;
				TransitionEditPart transitionEditPart = (TransitionEditPart) arcEditPart2.getTarget();
				if (!transitions.contains(transitionEditPart)) transitions.add(transitionEditPart);
			}
		}
		for (TransitionEditPart editPart : transitions) {
			editPart.refresh();
		}
	}
}
